package com.cssl.util;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CarGoodsUtil {

    public static Map<Integer, List<Map>> merge(List<Map> cartList) {
        List<Map<String, Object>> mergedCartList = new ArrayList<>();
        List<Integer> deletedNum = new ArrayList<>();
        for (int i = 0; i < cartList.size(); i++) {
            Map<String, Object> currentItem = cartList.get(i);
            Integer goodsId = (Integer) currentItem.get("productId");

            boolean isMerged = false;
            for (Map<String, Object> item : mergedCartList) {
                if (goodsId.equals(item.get("productId"))) {
                    // 合并数量
                    int newCartNumber = (Integer) item.get("cartNumber") + (Integer) currentItem.get("cartNumber");
                    item.put("cartNumber", newCartNumber);
                    isMerged = true;
                    deletedNum.add(i); // 记录删除的下标
                    break;
                }
            }
            if (!isMerged) {
                // 如果没有合并，添加到新列表
                mergedCartList.add(new HashMap<>(currentItem)); // 复制当前项
            }
        }
        // 删除已合并的项
        // 遍历时从最后一个索引开始删除，以避免删除时影响索引
        for (int i = deletedNum.size() - 1; i >= 0; i--) {
            int index = deletedNum.get(i);
            cartList.remove(index);
        }
        cartList.addAll(mergedCartList);
        Map<String, List<Map>> groupedByBrandId = mergedCartList.stream()
                .collect(Collectors.groupingBy(
                        item -> String.valueOf(item.get("brandId"))
                ));

        Map<Integer, List<Map>> result = groupedByBrandId.entrySet().stream()
                .collect(Collectors.toMap(
                        entry -> Integer.parseInt(entry.getKey()), // 将 String 转换为 Integer
                        Map.Entry::getValue // 获取对应的 List<Map>
                ));
        return result;
    }
}
